package com.yuanian.timingwheel.model.slot;

import com.yuanian.timingwheel.model.task.base.Task;
import com.yuanian.timingwheel.threadpool.ThreadPoolExecutorFactory;
import java.util.concurrent.ConcurrentLinkedQueue;

/**
 * 时间轮上的槽
 */
public class Slot {

    private ConcurrentLinkedQueue<Task> taskQueue;

    public Slot() {
    }

    /**
     * 添加任务
     */
    public void push(Task e){
        if(this.taskQueue == null){
            this.taskQueue = new ConcurrentLinkedQueue<>();
        }
        this.taskQueue.offer(e);
    }

    /**
     * 获取任务
     */
    public Task pop(){
        return isEmpty() ? null : taskQueue.poll();
    }

    public boolean isEmpty(){
        return this.taskQueue == null || this.taskQueue.isEmpty();
    }

    public void executeTask() {
       while (!isEmpty()) {
           //弹出任务并执行
           Task cur = taskQueue.poll();
           ThreadPoolExecutorFactory.getThreadPool().execute(() -> {
               System.out.println("开始执行任务，线程名：" + Thread.currentThread().getName() + "  线程池等待队列数量：" + ThreadPoolExecutorFactory.queue.size());
               cur.execute();
           });
       }
    }

}
